package com.xuecheng.manage_media.service.impl;

import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_media.dao.MediaFileRepository;
import com.xuecheng.manage_media.service.MediaFileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * @author Kidy
 * @date 2020/7/10 21:05
 */
@Service
public class MediaFileServiceImpl implements MediaFileService {


    @Autowired
    private MediaFileRepository mediaFileRepository;

    @Override
    public QueryResponseResult<MediaFile> findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        MediaFile mediaFile = new MediaFile();
        if (null != queryMediaFileRequest) {
            if (StringUtils.isNotBlank(queryMediaFileRequest.getFileOriginalName())) {
                mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
            }
            if (StringUtils.isNotBlank(queryMediaFileRequest.getProcessStatus())) {
                mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
            }
            if (StringUtils.isNotBlank(queryMediaFileRequest.getTag())) {
                mediaFile.setTag(queryMediaFileRequest.getTag());
            }
        }
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<MediaFile> example = Example.of(mediaFile, exampleMatcher);
        Page<MediaFile> mediaFilePage = mediaFileRepository.findAll(example, PageRequest.of(page - 1, size));

        QueryResult<MediaFile> mediaFileQueryResult = new QueryResult<>();
        mediaFileQueryResult.setTotal(mediaFilePage.getTotalElements());
        mediaFileQueryResult.setList(mediaFilePage.getContent());
        return new QueryResponseResult<MediaFile>(CommonCode.SUCCESS, mediaFileQueryResult);
    }
}
